package cn.explink.dop.controller.app;

import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.explink.dop.entity.vo.AppPushVO;
import cn.explink.dop.entity.vo.OrderVO;
import cn.explink.eap.core.constant.Globals;
import cn.explink.eap.core.extend.datasource.DataSourceContextHolder;
import cn.explink.eap.core.extend.datasource.DataSourceType;
import cn.explink.eap.core.util.ContextHolderUtils;
import cn.explink.eap.core.util.IpUtil;
import cn.explink.eap.web.system.manager.ClientManager;
import cn.explink.eap.web.system.pojo.base.Client;
import cn.explink.eap.web.system.pojo.base.TSUser;
import cn.explink.eap.web.system.service.SystemService;
import cn.explink.eap.web.system.service.UserService;

/**
 *
 * @author songkaojun 2015年3月19日
 */
@Controller
@RequestMapping("/loginController4App")
public class LoginController4App {

	@Autowired
	private UserService userService;

	@Autowired
	private SystemService systemService;

	/**
	 *
	 * @Title: login
	 * @Description: 用户登录，tags为推送标签，meId为手机唯一序列号
	 * @author 孟凡岭
	 * @param @param username
	 * @param @param password
	 * @param @param tags
	 * @param @param meId
	 * @param @param request
	 * @param @return
	 * @return TSUser 返回类型
	 * @throws
	 */
	@RequestMapping(params = "login")
	@ResponseBody
	public TSUser login(String username, String password, String tags, String meId, HttpServletRequest request) {
		TSUser u = new TSUser();
		if ((null == username) || (null == password)) {
			return u;
		}
		try {
			HttpSession session = ContextHolderUtils.getSession();
			DataSourceContextHolder.setDataSourceType(DataSourceType.dataSource_jeecg);
			// AjaxJson ajaxJson = new AjaxJson();
			int users = this.userService.getList(TSUser.class).size();
			if (users == 0) {
				// ajaxJson.setMsg("a");
				// ajaxJson.setSuccess(false);
			} else {
				TSUser userParam = new TSUser();
				userParam.setUserName(username);
				userParam.setPassword(password);
				u = this.userService.checkUserExits(userParam);
				if (u != null) {
					String message = "用户: " + userParam.getUserName() + "登录成功";
					Client client = new Client();
					client.setIp(IpUtil.getIpAddr(request));
					client.setLogindatetime(new Date());
					client.setUser(u);
					ClientManager.getInstance().addClinet(session.getId(), client);

					// ajaxJson.setObj(u);
					// 添加登陆日志
					this.systemService.addLog(message, Globals.Log_Type_LOGIN, Globals.Log_Leavel_INFO);
					AppPushVO push = new AppPushVO();
					push.setAlias(username);
					push.setMeId(meId);
					push.setTags(tags);
					this.userService.saveOrUpdate(push);
				} else {
					// ajaxJson.setMsg("用户名或密码错误!");
					// ajaxJson.setSuccess(false);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return u;
	}

	@RequestMapping(params = "ssoLogin")
	@ResponseBody
	public TSUser ssoLogin(String username, String password, HttpServletRequest request) {
		TSUser u = new TSUser();
		if ((null == username) || (null == password)) {
			return u;
		}
		try {
			HttpSession session = ContextHolderUtils.getSession();
			DataSourceContextHolder.setDataSourceType(DataSourceType.dataSource_jeecg);
			// AjaxJson ajaxJson = new AjaxJson();
			int users = this.userService.getList(TSUser.class).size();
			if (users == 0) {
				// ajaxJson.setMsg("a");
				// ajaxJson.setSuccess(false);
			} else {
				TSUser userParam = new TSUser();
				userParam.setUserName(username);
				userParam.setPassword(password);
				u = this.userService.checkUserExits(userParam);
				if (u != null) {

					String token = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
					u.setToken(token);
					u.setSsoFlag(1);
					this.userService.updateToken(u.getId(), token);
					String message = "用户: " + userParam.getUserName() + " 登录成功";
					Client client = new Client();
					client.setIp(IpUtil.getIpAddr(request));
					client.setLogindatetime(new Date());
					client.setUser(u);
					ClientManager.getInstance().addClinet(session.getId(), client);

					// ajaxJson.setObj(u);
					// 添加登陆日志
					this.systemService.addLog(message, Globals.Log_Type_LOGIN, Globals.Log_Leavel_INFO);
				} else {
					// ajaxJson.setMsg("用户名或密码错误!");
					// ajaxJson.setSuccess(false);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return u;
	}

	@RequestMapping(params = "getOrder")
	@ResponseBody
	public Map<String, Object> getOrder(String userId, String token, HttpServletRequest request) {
		TSUser u = this.userService.get(TSUser.class, userId);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("ssoFlag", this.checkToken(u, token));
		map.put("orderList", new ArrayList<OrderVO>());
		return map;

	}

	public int checkToken(TSUser u, String token) {
		/**
		 * 如果不相等说明不是同一台手机登录
		 */
		if (!token.equals(u.getToken())) {
			token = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			u.setToken(token);
			u.setSsoFlag(2);
			this.userService.updateToken(u.getId(), token);
			return 2;
		}
		return 1;
	}

	/**
	 *
	 * @Title: getApkVersion
	 * @Description: 获取APK版本
	 * @author 孟凡岭
	 * @param @return
	 * @return Map<String,Object> 返回类型
	 * @throws
	 */
	@SuppressWarnings("resource")
	@RequestMapping(params = "getApkVersion")
	@ResponseBody
	public Map<String, Object> getApkVersion(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String path = request.getSession().getServletContext().getRealPath("/") + "/apk/version.xml";
		try {
			FileInputStream fis = new FileInputStream(path.replace("\\", "/"));
			byte[] b = new byte[fis.available()];
			fis.read(b);
			String str = new String(b);

			Document doc = DocumentHelper.parseText(str);

			map = LoginController4App.Dom2Map(doc);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return map;

	}

	@SuppressWarnings("rawtypes")
	public static Map<String, Object> Dom2Map(Document doc) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (doc == null) {
			return map;
		}
		Element root = doc.getRootElement();
		for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
			Element e = (Element) iterator.next();
			List list = e.elements();
			if (list.size() > 0) {
				map.put(e.getName(), LoginController4App.Dom2Map(e));
			} else {
				map.put(e.getName(), e.getText());
			}
		}
		return map;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Map Dom2Map(Element e) {
		Map map = new HashMap();
		List list = e.elements();
		if (list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Element iter = (Element) list.get(i);
				List mapList = new ArrayList();

				if (iter.elements().size() > 0) {
					Map m = LoginController4App.Dom2Map(iter);
					if (map.get(iter.getName()) != null) {
						Object obj = map.get(iter.getName());
						if (!obj.getClass().getName().equals("java.util.ArrayList")) {
							mapList = new ArrayList();
							mapList.add(obj);
							mapList.add(m);
						}
						if (obj.getClass().getName().equals("java.util.ArrayList")) {
							mapList = (List) obj;
							mapList.add(m);
						}
						map.put(iter.getName(), mapList);
					} else {
						map.put(iter.getName(), m);
					}
				} else {
					if (map.get(iter.getName()) != null) {
						Object obj = map.get(iter.getName());
						if (!obj.getClass().getName().equals("java.util.ArrayList")) {
							mapList = new ArrayList();
							mapList.add(obj);
							mapList.add(iter.getText());
						}
						if (obj.getClass().getName().equals("java.util.ArrayList")) {
							mapList = (List) obj;
							mapList.add(iter.getText());
						}
						map.put(iter.getName(), mapList);
					} else {
						map.put(iter.getName(), iter.getText());
					}
				}
			}
		} else {
			map.put(e.getName(), e.getText());
		}
		return map;
	}
}
